package com.gradle.quartz.batch.partitioner;

import org.springframework.batch.core.partition.support.Partitioner;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户文件读取分区器
 * 作用：指定从步骤名称+配置从步骤需要的上下文环境
 *
 * @author ldanniel
 */
@Component
public class CustomerPartitioner implements Partitioner {
    /**
     * map: key :从步骤名称，value：从步骤上下文环境
     *
     * @param gridSize 从步骤个数
     * @return Map<String, ExecutionContext>
     */
    @Override
    public Map<String, ExecutionContext> partition(int gridSize) {
        String text = "--- CustomerPartitioner --- 第%s分区 --- 开始：%s ---- 结束：%s ---- 数据量 %s ----";
        Map<String, ExecutionContext> map = new HashMap<>();
        //将 from to range三个参数设置到上下文中
        int from = 1;
        int to = 1000;
        int range = 10000;
        for (int i = 0; i < gridSize; i++) {
            System.out.println(String.format(text, i, from, to, (to - from + 1)));
            ExecutionContext ec = new ExecutionContext();
            ec.putInt("startIndex", from);
            ec.putInt("toIndex", to);
            ec.putInt("range", range);
            to += range;
            from += range;
            map.put("employeePartition_" + i, ec);
        }
        return map;
    }

//    private Map<String, ExecutionContext> getStringExecutionContextMap(int gridSize) {
//        Map<String, ExecutionContext> map = new HashMap<>();
//        try {
//            for (int i = 0; i < gridSize; i++) {
//                String name = "user-" + i + ".txt";
//                ExecutionContext ec = new ExecutionContext();
//                Resource resource = new ClassPathResource("file/" + name);
//                ec.put("file", resource.getURL().toExternalForm());
//                map.put("userPartition_" + i, ec);
//            }
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//        }
//        return map;
//    }
}
